package com.iplant.mes.controller.sfc;

import com.alibaba.fastjson.JSON;
import com.iplant.ams.service.po.dms.scada.para.DMSDeviceRealParameter;
import com.iplant.base.po.ServiceResult;
import com.iplant.base.utils.RetCode;
import com.iplant.base.utils.serializer.CloneTool;
import com.iplant.base.utils.general.StringUtils;
import com.iplant.basic.controller.BasicController;
import com.iplant.basic.service.po.bms.BMSEmployee;
import com.iplant.mes.service.SFCFrockBindService;
import com.iplant.mes.service.SFCService;
import com.iplant.mes.service.po.constants.MESConstants;
import com.iplant.mes.service.po.sfc.SFCStationInterfaceLog;
import com.iplant.mes.service.po.sfc.SFCTaskStartCheck;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 开工检查
 *
 * @author YouWang·Peng
 * 2023-9-20 09:55:05
 */
@RestController
@RequestMapping("/api/SFCTaskStartCheck")
public class SFCTaskStartCheckController extends BasicController<SFCTaskStartCheck> {
    private static final Logger logger = LoggerFactory.getLogger(SFCTaskStartCheckController.class);

    public SFCTaskStartCheckController() {
        super(SFCTaskStartCheck.class);
    }

    @Autowired
    SFCService mSFCService;

    @Autowired
    SFCFrockBindService mSFCFrockBindService;

    /**
     * 提交开工检查记录
     */
    @PostMapping("/SubmitRecord")
    public Object SubmitRecord(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            SFCTaskStartCheck wSFCTaskStartCheck = CloneTool.Clone(wParam.get("data"), SFCTaskStartCheck.class);
            if (wSFCTaskStartCheck == null) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            Calendar wRequestTime = Calendar.getInstance();

            ServiceResult<Integer> wServiceResult = mSFCService.SFC_SubmitTaskStartCheckRecord(wLoginUser,
                    wSFCTaskStartCheck);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }

            Calendar wResponseTime = Calendar.getInstance();

            //维护工位实时接口日志
            Optional<SFCStationInterfaceLog> wOption =
                    MESConstants.StationInterfaceLogList.stream().filter(p -> p.StationID == wSFCTaskStartCheck.StationID
                            && p.InterfaceType.equals("工单开工检查")).findFirst();
            if (wOption.isPresent()) {
                SFCStationInterfaceLog sfcStationInterfaceLog = wOption.get();
                sfcStationInterfaceLog.OperatorID = wLoginUser.ID;
                sfcStationInterfaceLog.OperatorName = wLoginUser.Name;
                sfcStationInterfaceLog.InterfaceInput = JSON.toJSONString(wParam);
                sfcStationInterfaceLog.InterfaceOutput = JSON.toJSONString(wResult);
                sfcStationInterfaceLog.RequestTime = wRequestTime;
                sfcStationInterfaceLog.ResponseTime = wResponseTime;
            } else {
                SFCStationInterfaceLog wSFCStationInterfaceLog =
                        new SFCStationInterfaceLog(wSFCTaskStartCheck.StationID, wSFCTaskStartCheck.StationName,
                        wSFCTaskStartCheck.StationCode, wLoginUser.ID, wLoginUser.Name, JSON.toJSONString(wParam),
                                JSON.toJSONString(wResult), wRequestTime,
                        wResponseTime
                        , "工单开工检查");
                MESConstants.StationInterfaceLogList.add(wSFCStationInterfaceLog);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    /**
     * 根据工单获取设备实时参数
     */
    @GetMapping("/QueryParamsByTaskID")
    public Object QueryParamsByTaskID(HttpServletRequest request) {
        Object wResult = new Object();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            // 获取参数
            int wTaskSelfID = StringUtils.parseInt(request.getParameter("TaskSelfID"));
            if (wTaskSelfID <= 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            ServiceResult<List<DMSDeviceRealParameter>> wServiceResult =
                    mSFCService.SFC_QueryParamsByTaskID(wLoginUser, wTaskSelfID);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServiceResult.Result, null);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }

    /**
     * 查询单条数据
     */
    @GetMapping("/Info")
    public Object Info(HttpServletRequest request) {
        Object wResult = new Object();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            int wTaskSelfID = StringUtils.parseInt(request.getParameter("TaskSelfID"));
            if (wTaskSelfID <= 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            ServiceResult<SFCTaskStartCheck> wServiceResult =
                    mSFCFrockBindService.SFC_QueryTaskStartCheckInfo(wLoginUser, wTaskSelfID);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }
}
